package cn.com.yang.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 重定向服务器
 * TODO
 * @author yangyijin
 * @since 2023年5月14日-下午11:20:09
 */
public class HTTPRedirector {
	private static final Logger logger = Logger.getLogger("HTTPRedirector");
	private final int port;
	private final String newSite;
	public HTTPRedirector(int port, String newSite) {
		super();
		this.port = port;
		this.newSite = newSite;
	}
	public void start() {
		try(ServerSocket server = new ServerSocket(port)) {
			logger.info("Redirecting connetctions on port "+server.getLocalPort()+" to "+newSite);
			while(true) {
				try {
					Socket s = server.accept();
					Thread t = new RedirectThread(s);
					t.start();
				} catch (IOException e) {
					logger.warning("Exception accepting connection");
				}catch (RuntimeException e) {
					logger.log(Level.SEVERE,"Unexpected error ",e);
				}
			}
		} catch (BindException e) {
			logger.log(Level.SEVERE,"cound not start server.",e);
		} catch (IOException e) {
			logger.log(Level.SEVERE,"Error opening server socket",e);
		}
	}
	
	private class RedirectThread extends Thread{
		private final Socket conn;
		RedirectThread(Socket conn){
			this.conn = conn;
		}
		@Override
		public void run() {
			try (Writer out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"US-ASCII"));
				 Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))){
				//只读取第一行，这就是全部内容
				StringBuilder request = new StringBuilder(80);
				while(true) {
					int c = in.read();
					if (c=='\r'||c=='\n'||c==-1) {
						break;
					}
					request.append((char)c);
				}
				String get  = request.toString();
				String [] pipces = get.split("\\w*");// 这是什么字符
				String theFile = pipces[1];
				//如果是HTTP/1.0或者以后的版本，则发送一个MIME首部
				if (get.indexOf("HTTP")!=-1) {
					out.write("HTTP/1.0 302 FOUND\r\n");
					Date now = new Date();
					out.write("Server: Redirector 1.1\r\n");
					out.write("Location: "+newSite + theFile+"\r\n");
					out.write("Content-type: text/html\r\n\r\n");
					out.flush();
				}
				//并不是所有的浏览器支持重定向，所以我们需要
				//生成HTML文档转移到哪里
				out.write("<HTML><HEAD><TITLE>Document moved</TITLE></HEAD>\r\n");
				out.write("<BODY><H1>Document moved</H1>\r\n");
				out.write("The document "+theFile +" has moved to\r\n<A HREF=\""+newSite+theFile+"\">");
				out.write("</BODY></HTML>\r\n");
				out.flush();
				logger.log(Level.INFO,"Redireted "+conn.getRemoteSocketAddress());
			} catch (IOException e) {
				logger.log(Level.WARNING,"Error talking to "+conn.getRemoteSocketAddress(),e);
			}finally {
				try {
					conn.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
	
	public static void main(String[] args) {
		int thePort;
		String theSite;
		try {
			theSite = args[0];
			//删除末尾的斜线
			if (theSite.endsWith("/")) {
				theSite = theSite.substring(0,theSite.length()-1);
			}
		} catch (Exception e) {
			System.out.println("Usage: java Redirector http://www.newsite.com/ port");
			return;
		}
		try {
			thePort = Integer.parseInt(args[1]);
		} catch (Exception e) {
			thePort = 80;
		}
		HTTPRedirector redirector = new HTTPRedirector(thePort, theSite);
		redirector.start();
	}
}
